package com.nwpu.coursesupport.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.nwpu.coursesupport.enumeration.StatusType;
import com.nwpu.coursesupport.tool.WebUtils;

public class ExceptionHandler extends SimpleMappingExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object arg2,
			Exception ex) {

		if (ex instanceof MaxUploadSizeExceededException) {
			WebUtils.sendJson(response, StatusType.WRONG, "文件过大");
		}
		
		if((request.getHeader("accept").contains("application/json")
				|| (request.getHeader("X-Requested-With") != null
				&& request.getHeader("X-Requested-With").contains("XMLHttpRequest")))){
			WebUtils.sendJson(response, StatusType.WRONG, ex.getMessage());
			return null;
		}
		// 其他异常
		String viewName = determineViewName(ex, request);
		response.setCharacterEncoding("UTF-8");
		if (viewName != null) {// JSP格式返回
			Integer statusCode = determineStatusCode(request, viewName);
			if (statusCode != null) {
				applyStatusCodeIfPossible(request, response, statusCode);
			}
			return getModelAndView(viewName, ex, request);
		} else {
			return null;
		}
	}

}
